//
//  MainViewController.swift
//  新浪微博
//
//  Created by mac on 15/11/3.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController  {
    // MARK: - 监听方法
    /// 点击撰写按钮
    /// 如果`单纯`使用 `private` 运行循环将无法正确发送消息，导致崩溃
    /// 如果使用 @objc 修饰符号，可以保证运行循环能够发送此消息，即使函数被标记为 private
    @objc private func clickButton(){
        
       //判断用户是否登录
        var vc: UIViewController
        if UserAccountViewModel.sharedUserAccount.userLogon {
            vc = ComposeViewController()
        } else {
            vc = OAuthViewController()
        }
        
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
        // Do any additional setup after loading the view.
        addComposedButtton()
       
    }

    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(composedButton)
    }
    //MARK: 懒加载按钮控件
    private lazy var composedButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
}
    //MARK:  设置界面
    extension MainViewController{
    
        ///添加按钮并设置 frame
        private func addComposedButtton(){
            
            tabBar.addSubview(composedButton)
            
            let count = childViewControllers.count
            
            let w = tabBar.bounds.width / CGFloat(count) - 1
            
            composedButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
            
            //添加按钮监听方法
            composedButton.addTarget(self, action: "clickButton", forControlEvents: UIControlEvents.TouchUpInside)
        }
    
    
        ///创建自控制器并添加到tabar 上
    private func addChildViewControllers(){
        tabBar.tintColor = UIColor.orangeColor()
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
        
    }
    //创建单个
    private func addChildViewController(childController: UIViewController, title: String, imageName:String) {
        
        childController.title = title
        
        childController.tabBarItem.image = UIImage(named: imageName)
        let nav = UINavigationController(rootViewController: childController)
        addChildViewController(nav)
    }

}
